package test;

import java.util.Collection;
import java.util.Map;

public class SUSImpl implements SUS {
	@Override
	public <M extends Map<String, String>> M get(Collection<String> samples, M map) {
		String[] tmpdata = new String[samples.size()];
		int tmpsize = 0;
		for (String sample : samples) {
			tmpdata[tmpsize] = sample;
			tmpsize += 1;
		}
		for (int i = 0; i < tmpsize; ++i) {
			String tmpi = tmpdata[i];
			if (tmpi != null) {
				inner: for (int j = 0; j < tmpsize; ++j) {
					if (i != j) {
						String tmpj = tmpdata[j];
						if (tmpj != null) {
							if (tmpj.contains(tmpi)) {
								tmpdata[i] = null;
								break inner;
							}
						}
					}
				}
			}
		}
		{
			int j = 0;
			while (j < tmpsize && tmpdata[j] != null) ++j;
			for (int i = j + 1; i < tmpsize; ++i) {
				String tmpi = tmpdata[i];
				if (tmpi != null) {
					tmpdata[j] = tmpi;
					++j;
				}
			}
			tmpsize = j;
		}
		for (int i = 0; i < tmpsize; ++i) {
			String tmpi = tmpdata[i];
			outer: for (int s = 1, ss = tmpi.length() + 1; s < ss; ++s) {
				for (int f = 0, ff = ss - s; f < ff; ++f) {
					String candidate = tmpi.substring(f, f + s);
					inner: for (int j = 0; j < tmpsize; ++j) {
						if (i != j) {
							if (tmpdata[j].contains(candidate)) {
								candidate = null;
								break inner;
							}
						}
					}
					if (candidate != null) {
						String prev = map.put(candidate, tmpi);
						assert prev == null : "[" + prev + "] [" + tmpi + "] [" + candidate + "]";
						break outer;
					}
				}
			}
		}
		return map;
	}
}
